<template>
  <!-- 任务列表页面 -->
  <div v-if="!showTest">
    <!-- 刷新按钮 -->
    <div class="mb-20px flex justify-start">
      <el-button
        type="primary"
        :icon="Refresh"
        @click="refreshTasks"
        :loading="refreshing"
        class="transition-all duration-200 hover:scale-105"
      >
        刷新任务
      </el-button>
    </div>

    <!-- 任务网格 -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-20px">
      <div
        v-for="(t, index) in tasks"
        :key="t.id"
        class="p-24px rounded-16px shadow bg-white transition-all duration-300 hover:shadow-lg hover:scale-105 cursor-pointer animate-fade-in-up"
        :style="{ animationDelay: `${index * 0.1}s` }"
      >
        <div class="text-20px font-700 mb-12px" style="color: black">{{ t.jobName }}</div>
        <div class="text-16px mb-6px" style="color: black">
          题库数量：<b>{{ t.storeInfoList?.length || 0 }}</b>
        </div>
        <div class="text-16px mb-16px" style="color: black">
          关联算法：<b>{{ t.algorithmName }}</b>
        </div>
        <div class="text-16px mb-16px" style="color: black">
          练习次数：<b>{{ t.hisCount }}</b>
        </div>
        <div class="flex items-center gap-12px mt-10px">
          <!-- 已完成的任务：显示查看结果和重新测试 -->
          <template v-if="t.isCompleted">
            <el-button
              type="success"
              @click="viewResult(t)"
              class="transition-all duration-200 hover:scale-110 active:scale-95"
            >
              查看结果
            </el-button>
            <el-button
              type="primary"
              @click="startTask(t)"
              class="transition-all duration-200 hover:scale-110 active:scale-95"
            >
              重新测试
            </el-button>
          </template>

          <!-- 未完成的任务：显示开始测试 -->
          <el-button
            v-else
            type="primary"
            @click="startTask(t)"
            class="transition-all duration-200 hover:scale-110 active:scale-95"
          >
            开始测试
          </el-button>
        </div>
      </div>
    </div>
  </div>
  <ConsentDialog
    v-model="showConsent"
    :job-id="currentTaskId"
    :consent-data="consentTemplateData"
    @agree="agreeAndContinue()"
  />
  <!-- 在线测试页面 -->
  <OnlineTest
    v-if="showTest"
    :job-id="currentTaskId"
    @back="
      () => {
        showTest = false
        loadTasks()
      }
    "
  />
</template>

<script setup lang="ts">
import * as ExamTasksApi from '@/api/dt/examtasks'
import * as ConsentTemplateApi from '@/api/system/consenttemplate'
import { useUserStore } from '@/store/modules/user'
import { useRouter } from 'vue-router'
import ConsentDialog from './ConsentDialog.vue'
import OnlineTest from './OnlineTest.vue'
import { Refresh } from '@element-plus/icons-vue'

defineOptions({ name: 'DtExamTasks' })

const router = useRouter()
const message = useMessage()

const showConsent = ref(false)
const agreed = ref(false)
const showTest = ref(false)
const tasks = ref<any[]>([])
const currentTaskId = ref<number | null>(null)
const currentTask = ref<any>(null)
const refreshing = ref(false)
const userStore = useUserStore()
const consentTemplateData = ref<any>(null)

const agreeAndContinue = async () => {
  showTest.value =true
}

const loadTasks = async () => {
  const userId = userStore.user?.id
  const res = await ExamTasksApi.getExamTasks(userId)
  tasks.value = res
}

const refreshTasks = async () => {
  refreshing.value = true
  try {
    await loadTasks()
    message.success('任务列表已刷新')
  } catch (error) {
  } finally {
    refreshing.value = false
  }
}

const startTask = async (task: any) => {
  const userId = userStore.user?.id
  const data = await ExamTasksApi.examUserCheckConsent(userId, task.jobId)
  //显示测试页面，传递任务ID
  currentTaskId.value = task.jobId
  currentTask.value = task
  if (data) {
    showTest.value = true
  } else {
    try {
      const templateData = await ConsentTemplateApi.getConsentTemplate(task.consentFormTemplateId)
      consentTemplateData.value = templateData
      showConsent.value = true
    } catch (error) {
      console.error('获取配置失败:', error)
    }
  }
}

const viewResult = (task: any) => {
  // 跳转到结果页面，传递任务ID
  router.push({
    path: '/dt/dtuserexam',
    query: {
      jobId: task.jobId,
      taskName: task.jobName
    }
  })
}

onMounted(() => {
  //loadCheckConsent()
  loadTasks()
})
</script>

<style scoped>
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.animate-fade-in-up {
  animation: fadeInUp 0.6s ease-out forwards;
  opacity: 0;
}

/* 卡片悬停时的微妙光效 */
.hover\:shadow-lg:hover {
  box-shadow:
    0 10px 25px -5px rgba(0, 0, 0, 0.1),
    0 10px 10px -5px rgba(0, 0, 0, 0.04);
}

/* 按钮点击波纹效果 */
.el-button {
  position: relative;
  overflow: hidden;
}

.el-button::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 0;
  height: 0;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.3);
  transform: translate(-50%, -50%);
  transition:
    width 0.6s,
    height 0.6s;
}

.el-button:active::before {
  width: 300px;
  height: 300px;
}
</style>
